/*
 * Copyright 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package be.free.ts.activity.web;

import be.free.ts.web.MainPresenter;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import net.customware.gwt.presenter.client.EventBus;
import net.customware.gwt.presenter.client.place.PlaceRequest;
import net.customware.gwt.presenter.client.place.PlaceRequestEvent;
import net.customware.gwt.presenter.client.widget.WidgetDisplay;
import net.customware.gwt.presenter.client.widget.WidgetPresenter;

/**
 * @author Christophe De Blende
 * @since 05/01/13
 */
public class ActivityPresenter extends WidgetPresenter<ActivityPresenter.Display> implements ClickHandler {

	public interface Display extends WidgetDisplay {

		FlowPanel getContent();

		HasClickHandlers getSearch();

		HasClickHandlers getCreate();
	}

	private final MainPresenter mainPresenter;

	@Inject
	public ActivityPresenter(Display display, EventBus eventBus, MainPresenter mainPresenter) {
		super(display, eventBus);
		this.mainPresenter = mainPresenter;
	}

	@Override
	protected void onBind() {
		if (!mainPresenter.isBound()) {
			mainPresenter.bind();
			mainPresenter.revealDisplay();
		}

		display.getSearch().addClickHandler(this);
		display.getCreate().addClickHandler(this);

	}

	@Override
	protected void onUnbind() {
	}

	@Override
	protected void onRevealDisplay() {
		Panel content = mainPresenter.getDisplay().getContent();
		content.clear();
		content.add(display.asWidget());
	}

	@Override
	public void onClick(ClickEvent event) {
		Widget source = (Widget) event.getSource();
		if (source.getParent() == display.getSearch()) {
			eventBus.fireEvent(new PlaceRequestEvent(new PlaceRequest(ListActivitiesPlace.PLACE)));
		}
		if (source.getParent() == display.getCreate()) {
			eventBus.fireEvent(new PlaceRequestEvent(new PlaceRequest(CreateActivityPlace.PLACE)));
		}

	}
}
